package org.sean.framework.util;

import lombok.Data;

import java.security.SecureRandom;
import java.text.DecimalFormat;

/**
 * 红包算法
 * Created by Sean.xie on 2018/1/2.
 */
public class RedPacket {

    private RedPacket() {
    }

    /**
     * 随机金额
     *
     * @param packet packet
     * @return 随机金额
     */
    public static double getRandomPacket(Packet packet) {
        if (packet.remainSize == 1) {
            packet.remainSize--;
            return (double) Math.round(packet.remainMoney * 100) / 100;
        }
        SecureRandom r = new SecureRandom();
        double min = 0.01;
        double max = packet.remainMoney / packet.remainSize * 2;
        double money = r.nextDouble() * max;
        money = money <= min ? 0.01 : money;
        money = Math.floor(money * 100) / 100;
        packet.remainSize--;
        packet.remainMoney -= money;
        return money;
    }

    /**
     * 红包金额
     *
     * @param max 最大值
     * @return 随机金额
     */
    public static double getRandomPacket(double max) {
        return randomDouble(0, max);
    }

    /**
     * 红包金额
     *
     * @param min 最小值
     * @param max 最大值
     * @return 随机金额
     */
    public static double getRandomPacket(double min, double max) {
        return randomDouble(min, max);
    }

    /**
     * 生成随机数
     *
     * @param start 最小值
     * @param end   最大值
     * @return 随机金额
     */
    private static double randomDouble(double start, double end) {
        DecimalFormat df = new DecimalFormat("0.00");
        SecureRandom random = new SecureRandom();
        double rnd = start + random.nextDouble() * (end - start);
        if (NumberUtil.equals(rnd, start) || NumberUtil.equals(rnd, end)) {
            return randomDouble(start, end);
        }
        return Double.parseDouble(df.format(rnd));
    }

    /**
     * 生成红包
     *
     * @param remainSize  剩余个数
     * @param remainMoney 剩余金额
     * @return Packet
     */
    public Packet createPacket(int remainSize, double remainMoney) {
        return new Packet(remainSize, remainMoney);
    }

    /**
     * 红包
     */
    @Data
    public static class Packet {
        /**
         * 剩余的红包数量
         */
        private int remainSize;
        /**
         * 剩余的钱
         */
        private double remainMoney;

        public Packet() {
        }

        /**
         * @param remainSize  剩余个数
         * @param remainMoney 剩余金额
         */
        public Packet(int remainSize, double remainMoney) {
            this.remainSize = remainSize;
            this.remainMoney = remainMoney;
        }
    }
}
